#!/bin/sh

if [ $# -ne 2 ]
then
    echo "usage: $0 <start|stop> <config>" >&2
    exit 1
fi

action=$1
config=$2

gadget_name=mass-storage
gadget_dir=/sys/kernel/config/usb_gadget/$gadget_name

# Use GPIO to control USB signal on/off
set_usb_switch()
{
    if [ $1 = "OPEN" ]; then
        value=0
    elif [ $1 = "DISCONNECT" ]; then
        value=1
    else
        return -1
    fi

    gpioutil set USB_SWITCH $value
}

del_mass_storage()
{
    rm ${gadget_dir}/configs/c.1/mass_storage.usb0
    rmdir ${gadget_dir}/functions/mass_storage.usb0/
    rmdir ${gadget_dir}/configs/c.1/strings/0x409
    rmdir ${gadget_dir}/configs/c.1/
    rmdir ${gadget_dir}/strings/0x409/
    rmdir ${gadget_dir}
}

case "$config" in
0)
    nbd_device=/dev/nbd0
    ;;
1)
    nbd_device=/dev/nbd1
    ;;
*)
    echo "invalid config $config" >&2
    exit 1
    ;;
esac

case "$action" in
start)
    if [ -e "${gadget_dir}" ]; then
        cd $gadget_dir
        echo $nbd_device > functions/mass_storage.usb0/lun.0/file
        exit 0
    fi
    mkdir -p $gadget_dir
    (
    cd $gadget_dir
    # http://www.linux-usb.org/usb.ids
    #    |-> 1d6b  Linux Foundation
    #          |-> 0104  Multifunction Composite Gadget
    echo "0x1d6b" > idVendor
    echo "0x0104" > idProduct
    mkdir -p strings/0x409
    echo "OpenBMC" > strings/0x409/manufacturer
    echo "Virtual Media Device" > strings/0x409/product
    mkdir -p configs/c.1/strings/0x409
    echo "config 1" > configs/c.1/strings/0x409/configuration
    mkdir -p functions/mass_storage.usb0
    ln -s functions/mass_storage.usb0 configs/c.1
    echo 1 > functions/mass_storage.usb0/lun.0/removable
    echo 1 > functions/mass_storage.usb0/lun.0/ro
    echo 0 > functions/mass_storage.usb0/lun.0/cdrom
    echo $nbd_device > functions/mass_storage.usb0/lun.0/file
    echo "31900000.usb2" > UDC
    )
    ;;
stop)
    (
    cd $gadget_dir
    set_usb_switch "DISCONNECT"
    if [ $? -eq 0 ]; then
        # The USB physical path must be guaranteed to disconnected
        # in order to reset the vhub and remove the UDC.
	vhub_cfg=`devmem 0x319c0000`
	# Keep reset vhub(bit[12] = 0)
	devmem 0x319c0000 32 $(($vhub_cfg & ~(0x1 << 12)))
        echo "" > UDC
	# Release reset vhub(bit[12] = 1)
	devmem 0x319c0000 32 $(($vhub_cfg | (0x1 << 12)))
        set_usb_switch "OPEN"

        # Clear the mass_storage configuration
        del_mass_storage
    else
        # USB physical channel switching failures
        # should use a conservative scheme.
        # Note:
	# There are two problems with this:
        # 1.HOST exists an empty USB storage device.
        # 2.If the USB storage device is mount to
        # the HOST's file system, BMC cannot clear the file
        # and will affect the next mount file
        echo "" > functions/mass_storage.usb0/lun.0/file
    fi
    )
    ;;
*)
    echo "invalid action $action" >&2
    exit 1
esac

exit 0

